﻿using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Common;
using Hicap.AuthorizationServer.Core.Domains.Sys.Notification;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hicap.AuthorizationServer.Core.Notify
{
    public class NotifyHub : Hub
    {
        private readonly INotificationManager _notificationManager;
        private readonly IAbpSession _session;

        public NotifyHub(INotificationManager notificationManager)
        {
            _notificationManager = notificationManager;
            _session = NullAbpSession.Instance;
        }

        public List<string> Types { get; set; } = new List<string>
        {
            NotificationType.UserActive,
            NotificationType.UserForgetPassword
        };

        public override async Task OnConnectedAsync()
        {
            await Clients.All.SendAsync(NotificationMethod.Connected, $"{Context.ConnectionId} is Connected.");

            if (HaveActiveAuth())
            {
                Types.ForEach(async x =>
                {
                    await Groups.AddToGroupAsync(Context.ConnectionId, x);
                    List<Models.Sys.Notification> message = await _notificationManager.ReadMessage(x);
                    message.ForEach(async y => await SendToGroup(x, y.Id, y.MessageContent));
                    await base.OnConnectedAsync();
                });
            }
        }

        private bool HaveActiveAuth()
        {
            //            var claims = Context.User.Claims;
            string[] authCodes = _session.GetAuthCodes().Split(",");
            bool haveActiveAuth = authCodes != null && authCodes.Any(x => x.Equals(SpeicaAuthCode.UserActive));

            return haveActiveAuth;
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            Types.ForEach(async x =>
            {
                await Groups.RemoveFromGroupAsync(Context.ConnectionId, x);
            });
            await base.OnDisconnectedAsync(exception);
        }

        public async Task SendToGroup(string method, int messageId, string content)
        {
            if (string.IsNullOrEmpty(content)) return;

            var message = new { MessageId = messageId, Content = content };

            if (Clients == null) return;

            await Clients.Group(method).SendAsync(method, JsonConvert.SerializeObject(message));
        }
    }
}